import Vue from 'vue'
import Router from 'vue-router'
import Hero from '@/views/Hero'
import store from '@/store'
import Dashboard from '@/views/Dashboard'
import HeroDetail from '@/views/HeroDetail'
import Login from '@/views/Login'
import Layout from '@/views/Layout'

Vue.use(Router)

const routes = [
  { path: '',
    name: 'Layout',
    component: Layout
  },
  {
    path: '/heroes',
    name: 'Hero',
    component: Hero,
    meta: {
      title: 'Hero'
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: {
      title: 'Dashboard'
    }
  },
  {
    path: '/detail/:id',
    name: 'HeroDetail',
    component: HeroDetail,
    meta: {
      title: 'HeroDetail'
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: 'Login'
    }
  }
]

const router = new Router({
  mode: 'history',
  routes
})

router.beforeEach((to, from, next) => {
  console.log(store)
  const token = store.state.user.token
  if (token) {
    next()
  } else {
    console.log('未登录')
    if (to.name === 'Login') {
      console.log('跳转到登录页')
      next()
    } else {
      next('/login')
    }
  }
})

export default router
